package com.wmc.sqltransformweb.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wangmingchang.sqltransformbean.execute.SqlTranformBean;
import com.github.wangmingchang.sqltransformbean.pojo.dto.JavaPropertiesDto;
import com.github.wangmingchang.sqltransformbean.pojo.dto.MysqlPropertiesDto;
import com.github.wangmingchang.sqltransformbean.pojo.dto.TableDto;
import com.github.wangmingchang.sqltransformbean.util.MySQLTableUtil;
import com.wmc.sqltransformweb.pojo.request.JavaConfigListRequest;
import com.wmc.sqltransformweb.pojo.request.JavaConfigRequest;
import com.wmc.sqltransformweb.pojo.request.MysqlConfigRequest;
import com.wmc.sqltransformweb.pojo.request.PageRequest;
import com.wmc.sqltransformweb.pojo.response.BaseResponse;
import com.wmc.sqltransformweb.pojo.response.PageListDataResponse;
import com.wmc.sqltransformweb.pojo.vo.JavaConfigListVo;
import com.wmc.sqltransformweb.pojo.vo.JavaConfigVo;
import com.wmc.sqltransformweb.pojo.vo.MysqlConfigListVo;
import com.wmc.sqltransformweb.pojo.vo.MysqlConfigVo;
import com.wmc.sqltransformweb.service.SqlTransformService;
import com.wmc.sqltransformweb.utils.FileUtil;
import com.wmc.sqltransformweb.utils.ResponseEnum;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @auther wangmingchang
 * @date 2019/10/30 16:40
 */
@Log4j2
@Service
public class SqlTransformServiceImpl implements SqlTransformService {

    private static String mysqlConfigName= "mysql-config";
    private static String javaConfigName= "java-config";
    private static String leftSymbol = "[";
    private static String rightSymbol = "]";
    private static String lineFeed = "\r\n";
    private static String rootPate = "/data/sqlTransform";
    private static String fileType = "json";


    /**
     * 保存mysql配置
     *
     * @param request
     * @return
     */
    @Override
    public BaseResponse addMysqlConfig(MysqlConfigRequest request) {
        String jsonString = JSON.toJSONString(request);
        BaseResponse baseResponse = new BaseResponse(ResponseEnum.SUCCESS);
        boolean flag = false;
        String mysqlConfigPath = FileUtil.scanFile(rootPate, mysqlConfigName, fileType);;
        if(FileUtil.isExistFile(mysqlConfigPath)){
            flag = FileUtil.addJosnString(mysqlConfigPath, jsonString, request.getId());
        }else {
            flag = FileUtil.createJsonFile(jsonString,rootPate, mysqlConfigName);
        }
        if(!flag){
            baseResponse.setStatus(ResponseEnum.FAIL.getStatus());
            baseResponse.setMessage(ResponseEnum.FAIL.getMessage());
        }

        return baseResponse;
    }

    /**
     * 查询当前使用的mysql配置
     *
     * @return
     */
    @Override
    public BaseResponse getCurrentMysqlConfig() {
        URL classpath = Thread.currentThread().getContextClassLoader().getResource("");
        String classpathPath = classpath.getPath();
        log.info("当前classpath:{}, classpathPath：{}", classpath, classpathPath);
        BaseResponse baseResponse = new BaseResponse(ResponseEnum.NO_DATA);
        String mysqlConfigPath = FileUtil.scanFile(rootPate, mysqlConfigName, fileType);;
        if(FileUtil.isExistFile(mysqlConfigPath)){
            String currnetJsonData = FileUtil.getCurrnetJsonData(mysqlConfigPath);
            return new BaseResponse(ResponseEnum.SUCCESS, JSON.parseObject(currnetJsonData, MysqlConfigVo.class));
        }
        return baseResponse;
    }

    /**
     * 保存java配置
     *
     * @param request
     * @return
     */
    @Override
    public BaseResponse addJavaConfig(JavaConfigRequest request) {
        BaseResponse baseResponse = new BaseResponse(ResponseEnum.SUCCESS);
        boolean flag = false;
        String jsonString = JSON.toJSONString(request);
        String javaConfigPath = FileUtil.scanFile(rootPate, javaConfigName, fileType);;
        if(FileUtil.isExistFile(javaConfigPath)){
            flag = FileUtil.addJosnString(javaConfigPath, jsonString, request.getId());
        }else {
            flag = FileUtil.createJsonFile(jsonString,rootPate, javaConfigName);
        }
        if(!flag){
            baseResponse.setStatus(ResponseEnum.FAIL.getStatus());
            baseResponse.setMessage(ResponseEnum.FAIL.getMessage());
        }
        return baseResponse;
    }

    /**
     * 查询当前使用的java配置
     *
     * @return
     */
    @Override
    public BaseResponse getCurrentJavaConfig() {
        BaseResponse baseResponse = new BaseResponse(ResponseEnum.NO_DATA);
        String mysqlConfigPath = FileUtil.scanFile(rootPate, javaConfigName, fileType);
        if(FileUtil.isExistFile(mysqlConfigPath)){
            String currnetJsonData = FileUtil.getCurrnetJsonData(mysqlConfigPath);
            return new BaseResponse(ResponseEnum.SUCCESS, JSON.parseObject(currnetJsonData, JavaConfigVo.class));
        }
        return baseResponse;
    }

    /**
     * 执行生成器
     *
     * @return
     */
    @Override
    public BaseResponse addExecute() {
        BaseResponse currentMysqlConfig = getCurrentMysqlConfig();
        MysqlConfigVo mysqlConfigVo = (MysqlConfigVo) currentMysqlConfig.getData();
        if(null == mysqlConfigVo){
            return new BaseResponse(ResponseEnum.ERROR_DATA.getStatus(), "mysql没配置");
        }

        BaseResponse currentJavaConfig = getCurrentJavaConfig();
        JavaConfigVo javaConfigVo = (JavaConfigVo) currentJavaConfig.getData();
        if(null == javaConfigVo){
            return new BaseResponse(ResponseEnum.ERROR_DATA.getStatus(), "java没配置");
        }
        MysqlPropertiesDto mysqlPropertiesDto = new MysqlPropertiesDto();
        BeanUtils.copyProperties(mysqlConfigVo, mysqlPropertiesDto);
        JavaPropertiesDto javaPropertiesDto = new JavaPropertiesDto();
        BeanUtils.copyProperties(javaConfigVo, javaPropertiesDto);
        String tableName = javaPropertiesDto.getTableName();
        TableDto tableDto = null;
        try {
            tableDto = MySQLTableUtil.getColumnByTableName(tableName, mysqlPropertiesDto);
        }catch (Exception e){
            log.error("查询 [{}] 表信息异常", tableName,e);
        }
        if(null == tableDto){
            return new BaseResponse(ResponseEnum.FAIL.getStatus(),tableName + " 表信息不存在，请核实！");
        }
        SqlTranformBean.init(mysqlPropertiesDto, javaPropertiesDto);

        return new BaseResponse(ResponseEnum.SUCCESS.getStatus(),javaConfigVo.getTableName() + " 表转换成功！");
    }

    /**
     * 查询mysql配置列表信息
     *
     * @param pageRequest
     * @return
     */
    @Override
    public BaseResponse queryMsqlConfigList(PageRequest pageRequest) {
        URL classpath = Thread.currentThread().getContextClassLoader().getResource("");
        String classpathPath = classpath.getPath();
        log.info("当前classpath:{}, classpathPath：{}", classpath, classpathPath);
        BaseResponse baseResponse = new BaseResponse(ResponseEnum.NO_DATA);
        String mysqlConfigPath = FileUtil.scanFile(rootPate, mysqlConfigName, fileType);;
        if(FileUtil.isExistFile(mysqlConfigPath)){
            Map<String, Object> map = FileUtil.getListJsonData(mysqlConfigPath, JSON.parseObject(JSON.toJSONString(pageRequest), Map.class));
            PageListDataResponse<MysqlConfigListVo> response = new PageListDataResponse<>();
            List<MysqlConfigListVo> dataList = JSONObject.parseArray((String) map.get("dataList"), MysqlConfigListVo.class);
            if(null != dataList && dataList.size() > 1){
                Collections.sort(dataList, new Comparator<MysqlConfigListVo>() {
                    @Override
                    public int compare(MysqlConfigListVo o1, MysqlConfigListVo o2) {
                        return o1.getCreateTime() >= o2.getCreateTime() ? -1 : 1;
                    }
                });
            }
            response.setDataList(dataList);
            response.setPageNo(pageRequest.getPageNo());
            response.setPageSize(pageRequest.getPageSize());
            response.setPageCount((int) map.get("pageCount"));
            return new BaseResponse(ResponseEnum.SUCCESS, response);
        }
        return baseResponse;
    }

    /**
     * 更新mysql配置
     *
     * @param id
     * @return
     */
    @Override
    public BaseResponse updateMysqlConfig(String id) {
        BaseResponse baseResponse = new BaseResponse(ResponseEnum.FAIL);
        String mysqlConfigPath = FileUtil.scanFile(rootPate, mysqlConfigName, fileType);
        if(FileUtil.isExistFile(mysqlConfigPath)){
            boolean falseFlag = FileUtil.updateDataFalseById(mysqlConfigPath,id);
            boolean trueFlag = FileUtil.updateDataTrueById(mysqlConfigPath,id);
            if(falseFlag && trueFlag){
                return new BaseResponse(ResponseEnum.SUCCESS);
            }
        }
        return baseResponse;
    }

    /**
     * 删除mysql配置
     *
     * @param id
     * @return
     */
    @Override
    public BaseResponse deleteMysqlConfig(String id) {
        BaseResponse baseResponse = new BaseResponse(ResponseEnum.FAIL);
        String mysqlConfigPath = FileUtil.scanFile(rootPate, mysqlConfigName, fileType);
        if(FileUtil.isExistFile(mysqlConfigPath)){
            boolean flag = FileUtil.removeRow(mysqlConfigPath,id);
            if(flag){
                return new BaseResponse(ResponseEnum.SUCCESS);
            }
        }
        return baseResponse;
    }

    /**
     * 查询java配置列表信息
     *
     * @param request
     * @return
     */
    @Override
    public BaseResponse queryJavalConfigList(JavaConfigListRequest request) {
        URL classpath = Thread.currentThread().getContextClassLoader().getResource("");
        String classpathPath = classpath.getPath();
        log.info("当前classpath:{}, classpathPath：{}", classpath, classpathPath);
        BaseResponse baseResponse = new BaseResponse(ResponseEnum.NO_DATA);
        String javaConfigPath = FileUtil.scanFile(rootPate, javaConfigName, fileType);;
        if(FileUtil.isExistFile(javaConfigPath)){
            Map<String, Object> map = FileUtil.getListJsonData(javaConfigPath, JSON.parseObject(JSON.toJSONString(request), Map.class));
            PageListDataResponse<JavaConfigListVo> response = new PageListDataResponse<>();
            List<JavaConfigListVo> dataList = JSONObject.parseArray((String) map.get("dataList"), JavaConfigListVo.class);
            if(null != dataList && !dataList.isEmpty()){
                Collections.sort(dataList, new Comparator<JavaConfigListVo>() {
                    @Override
                    public int compare(JavaConfigListVo o1, JavaConfigListVo o2) {
                        return o1.getCreateTime() >= o2.getCreateTime() ? -1 : 1;
                    }
                });
            }
            response.setDataList(dataList);
            response.setPageNo(request.getPageNo());
            response.setPageSize(request.getPageSize());
            response.setPageCount((int) map.get("pageCount"));
            return new BaseResponse(ResponseEnum.SUCCESS, response);
        }
        return baseResponse;
    }

    /**
     * 更新java配置
     *
     * @param id
     * @return
     */
    @Override
    public BaseResponse updateJavaConfig(String id) {
        BaseResponse baseResponse = new BaseResponse(ResponseEnum.FAIL);
        String javaConfigPath = FileUtil.scanFile(rootPate, javaConfigName, fileType);
        if(FileUtil.isExistFile(javaConfigPath)){
            boolean falseFlag = FileUtil.updateDataFalseById(javaConfigPath,id);
            boolean trueFlag = FileUtil.updateDataTrueById(javaConfigPath,id);
            if(falseFlag && trueFlag){
                return new BaseResponse(ResponseEnum.SUCCESS);
            }
        }
        return baseResponse;
    }

    /**
     * 删除java配置
     *
     * @param id
     * @return
     */
    @Override
    public BaseResponse deleteJavaConfig(String id) {
        BaseResponse baseResponse = new BaseResponse(ResponseEnum.FAIL);
        String javaConfigPath = FileUtil.scanFile(rootPate, javaConfigName, fileType);
        if(FileUtil.isExistFile(javaConfigPath)){
            boolean flag = FileUtil.removeRow(javaConfigPath, id);
            if(flag){
                return new BaseResponse(ResponseEnum.SUCCESS);
            }
        }
        return baseResponse;
    }
}
